package com.example.chuntiao.cophook.ui;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.beans.Person;
import com.example.chuntiao.cophook.exception.RepeatException;
import com.example.chuntiao.cophook.mytools.HttpTool;

import java.io.IOException;

public class SignUpActivity extends AppCompatActivity implements TextWatcher {

    private static final String TAG = "SignUpActivity";
    EditText editUid;
    EditText editUname;
    EditText editPasswd;
    EditText editPasswdRepeat;
    EditText editPhone1;
    EditText editPhone2;
    EditText editLocate;
    TextView notMatch;
    CheckBox check;
    ImageView imgVisiablity;

    MenuItem itemSingUp;
    //View.OnClickListener listener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign_up);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



        editUid = (EditText) findViewById(R.id.edit_oid);
        editUid.addTextChangedListener(this);
        editUname = (EditText) findViewById(R.id.edit_uname);
        editUname.addTextChangedListener(this);
        editPasswd = (EditText) findViewById(R.id.edit_passwd);
        editPasswd.addTextChangedListener(this);
        editPasswdRepeat = (EditText) findViewById(R.id.edit_passwd_repead);
        editPasswdRepeat.addTextChangedListener(this);
        editPhone1 = (EditText) findViewById(R.id.edit_phone1);
        editPhone1.addTextChangedListener(this);

        editPhone2 = (EditText) findViewById(R.id.edit_phone2);
        editLocate = (EditText) findViewById(R.id.edit_locate);
        imgVisiablity = (ImageView) findViewById(R.id.img_invisiable);
        notMatch = (TextView) findViewById(R.id.txt_not_match);

        check = (CheckBox) findViewById(R.id.check_obay);
        check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkEmpty();
            }
        });


        imgVisiablity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (editPasswd.getInputType() == (InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD)) {
                    editPasswd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    editPasswdRepeat.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    ((ImageView) v).setImageResource(R.drawable.ic_action_visiable);
                } else {
                    editPasswd.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    editPasswdRepeat.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    ((ImageView) v).setImageResource(R.drawable.ic_action_invisiable);
                }

            }
        });

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.signup, menu);
        itemSingUp = menu.findItem(R.id.action_sing_up);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == R.id.action_sing_up) {
            final Person p = new Person();
            p.setUid(editUid.getText().toString());
            p.setName(editUname.getText().toString());
            p.setPhone1(editPhone1.getText().toString());
            p.setPhone2(editPhone2.getText().toString());
            p.setLocate(editLocate.getText().toString());

            final String passwd = editPasswd.getText().toString();

            new AsyncTask<Void, Void, Boolean>() {

                ProgressDialog dialog;
                int state = 0;
                static final int STA_SUCCESS = 0;
                static final int STA_NO_NET = 1;
                static final int STA_UID_REPEAT = 2;


                @Override
                protected void onPreExecute() {
                    dialog = new ProgressDialog(SignUpActivity.this);
                    dialog.setMessage("注册中");

                }

                @Override
                protected Boolean doInBackground(Void... params) {

                    try {
                        if (HttpTool.sendOkHttpSignUp(SignUpActivity.this, p, passwd))
                            return true;
                    } catch (RepeatException e) {
                        state = STA_UID_REPEAT;
                        return false;
                    } catch (IOException e) {
                        state = STA_NO_NET;
                        e.printStackTrace();
                        return false;
                    }
                    return null;
                }

                @Override
                protected void onPostExecute(Boolean result) {

                    dialog.dismiss();
                    if (result)
                        finish();
                    else if (state == STA_UID_REPEAT)
                        new AlertDialog.Builder(SignUpActivity.this)
                                .setTitle("抱歉")
                                .setMessage("抱歉，用户名重复，请修改后重试")
                                .setPositiveButton("确定", null)
                                .show();
                    else
                        new AlertDialog.Builder(SignUpActivity.this)
                                .setTitle("抱歉")
                                .setMessage("网络错误，请检查网络")
                                .setPositiveButton("确定", null)
                                .show();
                }
            }.execute();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        checkEmpty();
        checkMatch();
    }


    void checkEmpty() {
        String uid = editUid.getText().toString();
        String uname = editUname.getText().toString();
        String passwd = editPasswd.getText().toString();
        String passwdRepeat = editPasswdRepeat.getText().toString();
        String phone1 = editPhone1.getText().toString();

        if (uid.equals("") || uname.equals("") | passwd.equals("") || passwd.equals("") || passwdRepeat.equals("") || phone1.equals("")) {
            itemSingUp.setEnabled(false);
            return;
        }
        if (!passwd.equals(passwdRepeat)) {
            itemSingUp.setEnabled(false);
            return;
        }

        if (!check.isChecked()) {
            itemSingUp.setEnabled(false);
            return;
        }

        itemSingUp.setEnabled(true);

    }

    void checkMatch() {
        String passwd = editPasswd.getText().toString();
        String passwdRepeat = editPasswdRepeat.getText().toString();

        if (passwd.equals(passwdRepeat))
            notMatch.setVisibility(View.INVISIBLE);
        else
            notMatch.setVisibility(View.VISIBLE);
    }
}
